<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // push 从后面添加元素
      let a = []
      console.log(a.push(1)) // 1 打印的是数组的长度
      console.log(a.push(2)) // 2
      console.log(a.push(100)) //3
      // a.push(4,5,6)

      // pop  从后面删除元素
      console.log(a.pop()) // 100 返回弹出的那个元素
      console.log(a.pop()) //2
      console.log(a.pop()) //1
      console.log(a.pop()) //undefined

      // unshift  从前面添加元素
      console.log(a.unshift(1)) //1
      console.log(a.unshift(2)) //2
      console.log(a.unshift(100)) //3

      // shift 从前面删除元素
      console.log(a.shift()) //100
      console.log(a.shift()) //2
      console.log(a.shift()) //1
      console.log(a.shift()) //undefined

      // 实现字符串反转 reverse()
      let str = 'abcd'
      function reverse(str) {
        return str.split('').reverse().join('')
      }
      console.log(reverse(str))

      // 手写一个基于发布订阅的js事件处理中心
      let eventBus = {
        arrays: {
          click: [],
          scroll: [],
        },
        on: function (type, fn) {
          this.arrays[type] = this.arrays[type] || [] //arrays[type] 初始化为[]
          this.arrays[type].push(fn)
        },
        emit: function (type, data) {
          const a = this.arrays[type]
          if (!a) return // 防御式编程
          for (let i = 0; i < a.length; i++) {
            const fn = a[i]
            fn(data)
          }
        },
      }
      eventBus.on('click', function (data) {
        console.log('clicked:' + data)
      })
      setTimeout(function () {
        eventBus.emit('click', 'button#x')
      }, 3000)

      // splice 可以在数组的任何位置增和删 这种方法会改变原始数组
      let arr1 = [1, 2, 3]
      console.log(arr1.splice(2, 1)) // 3 //从索引2开始删除1个元素的数组
      console.log(arr1.splice(2, 0)) //删除0个 ，没有改变原数组
      console.log(arr1)
      console.log(arr1.splice(1, 1, 3)) //删除索引号1后面的1个元素 任何增加一个3
      console.log(arr1) // [1,3]
    </script>
  </body>
</html>
